What's the best way to return something like a collection of `std::auto_ptr`s in C++03?

Posted by Billy ONeal on Stack Overflow See other posts from Stack Overflow or by Billy ONeal
Published on 2010-12-25T20:51:48Z Indexed on 2010/12/25 20:54 UTC
Read the original article Hit count: 167

std::auto_ptr is not allowed to be stored in an STL container, such as std::vector. However, occasionally there are cases where I need to return a collection of polymorphic objects, and therefore I can't return a vector of objects (due to the slicing problem). I can use std::tr1::shared_ptr and stick those in the vector, but then I have to pay a high price of maintaining separate reference counts, and object that owns the actual memory (the container) no longer logically "owns" the objects because they can be copied out of it without regard to ownership.

C++0x offers a perfect solution to this problem in the form of std::vector<std::unique_ptr<t>>, but I don't have access to C++0x.

Some other notes:

  • I don't have access to C++0x, but I do have TR1 available.
  • I would like to avoid use of Boost (though it is available if there is no other option)
  • I am aware of boost::ptr_container containers (i.e. boost::ptr_vector), but I would like to avoid this because it breaks the debugger (innards are stored in void *s which means it's difficult to view the object actually stored inside the container in the debugger)

© Stack Overflow or respective owner

Related posts about c++

Related posts about memory-management